package generation

import (
	_ "embed"
	"fmt"
	"html/template"
	"io"
	"os"
	"path/filepath"
	"strings"

	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/rest"
)

const (
	packagejenkins = "jenkins"
	packagek8s     = "k8s"
)

//go:embed release_tpl/k8s/deployment.yaml
var DeploymentYml []byte

//go:embed release_tpl/k8s/service.yaml
var SerivceYml []byte

//go:embed release_tpl/jenkins/config.xml
var JenkinsXml []byte

type AutoCodeService struct{}

type autoPackage struct {
	path string
	temp string
}

func (autoCodeService *AutoCodeService) CreatePackageTemp(projectName, port, namespace, directory, giturl, env string) (string, error) {
	basePath := filepath.Join(directory, projectName+"-resources")

	pendingTemp := []autoPackage{{
		path: packagejenkins + "/config.xml",
		temp: string(JenkinsXml),
	}, {
		path: packagek8s + "/deployment.yaml",
		temp: string(DeploymentYml),
	}, {
		path: packagek8s + "/service.yaml",
		temp: string(SerivceYml),
	}}
	for i, s := range pendingTemp {
		pendingTemp[i].path = filepath.Join(basePath, s.path)
	}
	// 选择模板
	for _, s := range pendingTemp {
		err := os.MkdirAll(filepath.Dir(s.path), 0755)
		if err != nil {
			return "目录创建失败", err
		}

		f, err := os.Create(s.path)
		if err != nil {
			return "文件创建失败", err
		}

		defer f.Close()

		temp, err := template.New("").Parse(s.temp)
		if err != nil {
			return "模板生成失败", err
		}

		err = temp.Execute(f, struct {
			ProjectName string `json:"project_name"`
			Port        string `json:"port"`
			Namespace   string `json:"namespace"`
			GitUrl      string `json:"git_url"`
		}{projectName, port, namespace, giturl})
		if err != nil {
			return "模板写入失败", err
		}
	}

	jenkinsURL := "http://mind-jenkins.im30.lan"

	user := "sinuo"
	apiToken := "1159220fd638981bada2e8bb81d4088601"

	configXML, err := os.ReadFile(projectName + "-resources" + "/jenkins/config.xml")
	if err != nil {
		fmt.Println("Error reading config.xml:", err)
		return "Jenkins视图创建失败", err
	}

	createJob(jenkinsURL, user, apiToken, projectName, configXML)

	clusters := []ClusterConfig{
		{
			Name:        "dev",
			Server:      "https://10.0.5.11:6443",
			BearerToken: "eyJhbGciOiJSUzI1NiIsImtpZCI6IllEWUlTdEtUTENYNHJNdHF2QXZoYXZhYUlfOVBlRGQ3Rmp2Um9hMXY1YjAifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6InN1cGVyLWFkbWluLXNlY3JldCIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJzdXBlci1hZG1pbi1hY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiNTBlODQxYjYtNmRjOS00NjU0LThkMTMtODUyNTQ2YjM3NTY0Iiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmRlZmF1bHQ6c3VwZXItYWRtaW4tYWNjb3VudCJ9.L-EvmtWsYqe5qFkwZxOt9j1y8_P-evU56D9Uc2oJdTzYvEiJP3cDwX1C2HM0diES7twsgyT9oRAv-X1iaUzTJELrXGRHNr3Yev0SzXJ6CCde9-ZmJo-rcv822_vic_Cc1kzV0QHIc7rcuCE10txE8NhERgi4Sezr7faPkX8pBK8-AQiHKGBWwED5tASJ1FijkjJne9DDR82FTEUOSdOqgYJ6RHIyUEuSQaNWXZWtopDIhwLdj8vbg_TOS79EVp_4vM2bPR_6_C81aixwn_xpfN6vlJTNGYjobVYXwxMPsscb7xUHbd2Rolq4pa3Z9F8tqb23D7hO2qXnoAARCcHFcw",
		},
		{
			Name:        "pre",
			Server:      "https://cls-6dfgslzz.ccs.tencent-cloud.com",
			BearerToken: "eyJhbGciOiJSUzI1NiIsImtpZCI6Ikt2aFdaNFBPc3lIaHloNVlKZHRyei1MZW1YY1hUT3BMM01IZ182ZURmMU0ifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImF1dG8tYWRtaW4tdG9rZW4tbjc0Z3AiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiYXV0by1hZG1pbiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjkxZWJkNDRhLTRhZTktNGVkMS1iYTM4LWVmYjBiZWUzOTk0OCIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmF1dG8tYWRtaW4ifQ.wBTp_C1U9q2pbtRrkNNAw1Je0yTJzrsIrtuXE8stH019j4pGY0ITObv3MyJ8reWeF-lD6ulEbWN52Dz_DF3NeJC4dRVqqDUu9hqyRA6wkvEos5hLV-nsgkYTyw5IffImQN_rkbkz4PPp7D3Pngw6NVcY70UywQA1v3uCaiAt1Y0rHFf2N-wlEEHW-p-785tqvgu-SyZ43BUqBrP6qXoKJxRbN7QskeI73ICfru8LlRhK6xuzWsYRf2PPtFF0jQcv0Zn456fXA4r91YNrNMDtdypPt7jDbOOwxFQEOxTaeiSup8xrtncWBD9g7nIllni0vTL567BvkY5sN9J2ldsIrg",
		},
		{
			Name:        "prod",
			Server:      "https://cls-ewr0i52r.ccs.tencent-cloud.com",
			BearerToken: "eyJhbGciOiJSUzI1NiIsImtpZCI6InptU3E2TTVVVmhEaHZheUR0UkljVlBxZU1CTzlzZnhBRE80LThXNlhDUUEifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJkZWZhdWx0Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6ImF1dG8tYWRtaW4tdG9rZW4tN2ZxdG4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoiYXV0by1hZG1pbiIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjJkZGRmZDhmLTc5ZjItNGU5ZS04NmYxLWU0MmZmNjI3MWQwMSIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDpkZWZhdWx0OmF1dG8tYWRtaW4ifQ.PQQvi4aJLhUGO2Ugf2G6b-vZeSRqlnkSujB2jtz1t22_JWtBGIzg2ARxGsRRrslwsRgfQjImDoZ_Rsxk4UBBah9SdffaQB5QTimyYesYrnJu1UPoLHrzGwlSyGQC94wUPzXUhbG0bGtaCzEcMQa9FVAvOhWJzEgqZlrMebsJsjZMzSYJfD3C2dAz7x4utg6JO8u3BjoGz9NN1Kj3Od94UVNG2SaPUfdZ-Ampifwu4MxevxNoF71f3AOpYCK5uG2f_KYz5e_2Y03NwSsGpYeRrDEj_EHByp5N-vgBh-yclh9u3c7Z6bFudcJ3lKvoBvEqqtjUkSprz-YHBRkDn7M5lw",
		},
	}

	if env != "all" {
		switch env {
		case "dev":
			clusters = []ClusterConfig{clusters[0]}
			break
		case "pre":
			clusters = []ClusterConfig{clusters[1]}
			break
		case "prod":
			clusters = []ClusterConfig{clusters[2]}
			break

		}
	}

	// 部署的 YAML 文件
	deployFiles := []string{projectName + "-resources" + "/k8s/deployment.yaml", projectName + "-resources" + "/k8s/service.yaml"}

	// 循环处理每个集群
	for _, cluster := range clusters {
		fmt.Printf("部署到 %s 环境\n", cluster.Name)

		// 创建 REST 配置
		config := &rest.Config{
			Host:            cluster.Server,
			BearerToken:     cluster.BearerToken,
			TLSClientConfig: rest.TLSClientConfig{Insecure: true}, // 注意：仅在信任集群时使用 Insecure
		}

		// 创建动态客户端
		dynamicClient, err := dynamic.NewForConfig(config)
		if err != nil {
			panic(err.Error())
		}

		// 部署文件到当前集群
		for _, file := range deployFiles {
			if err := applyYaml(dynamicClient, file, namespace); err != nil {
				fmt.Println("yaml文件创建失败", err)
				continue // 出现错误时跳过当前文件
			}
		}
	}

	fmt.Printf("%v 环境全部部署完成\n", env)

	return "项目: " + "(" + projectName + ")" + " release自动化配置已生成于 " + basePath, nil
}

func (autoCodeService *AutoCodeService) CleanPackageTemp() (string, error) {
	// 读取当前路径下的release文件夹中Jenkinsfile文件中的name = 后的值
	f, err := os.Open("./release/Jenkinsfile")
	if err != nil {
		return "没有需要清理的release", nil
	}
	b, err := io.ReadAll(f)
	if err != nil {
		return "Jenkinsfile文件读取失败", err
	}
	name := strings.Split(strings.Split(string(b), "name = ")[1], " ")[0]
	name = strings.Split(name, "\"")[1]
	f.Close()

	err2 := os.RemoveAll("./release")
	if err2 != nil {
		return "release文件夹删除失败", err
	}

	return "项目: " + "(" + name + ")" + " release自动化配置已清理", nil
}
